import os
import zipfile
import json
from pathlib import Path


class GetInformation:

    @staticmethod
    def uncompress_zip(file_path: Path, dst_path: Path):
        """解压zip文件"""
        zip_name = file_path.stem
        dst_path = dst_path / zip_name
        print('dst_path:', dst_path)
        
        def extract_and_rename(z_file: zipfile.ZipFile, name, extension):
            z_file.extract(name, dst_path)
            old_name = dst_path / name
            new_name = dst_path / f"{zip_name}.{extension}"
            try:
                old_name.rename(new_name)
            except FileExistsError:
                new_name.unlink()
                old_name.rename(new_name)

        with zipfile.ZipFile(file_path, 'r') as z_file:
            for name in z_file.namelist():
                if name.endswith('.json'):
                    extract_and_rename(z_file, name, 'json')
                    json_path = dst_path / f"{zip_name}.json"
                    values = GetInformation.read_property(json_path)
                    txt_path = GetInformation.write_txt(values, dst_path)
                elif name.endswith('.svg'):
                    extract_and_rename(z_file, name, 'svg')
                elif name.endswith('.jpg'):
                    extract_and_rename(z_file, name, 'jpg')
                    jpg_path = dst_path / f"{zip_name}.jpg"

        return jpg_path, txt_path, json_path

    @staticmethod
    def read_property(file_path: Path):
        """从zip中提取json文件，解析并提取关键属性"""
        values = {}
        with open(file_path, 'r', encoding='utf-8') as f:
            data = json.load(f)

            try:
                # 订单ID
                orderId = data["orderId"]
                values['orderId'] = orderId
            except:
                values['orderId'] = '未读取到'

            try:
                # 子订单ID
                orderItemId = data["orderItemId"]
                values['orderItemId'] = orderItemId
            except:
                values['orderItemId'] = '未读取到'

            try:
                # 定制信息部分
                customizationData = data["customizationData"]['children'][0]['children'][0]['children']
            except:
                return

            try:
                Color = customizationData[0]['optionSelection']['label']
                values['Color'] = Color
            except:
                values['Color'] = '未读取到'

            try:
                Choose_Charm = customizationData[1]['optionSelection']['label']
                values['Choose_Charm'] = Choose_Charm
            except:
                values['Choose_Charm'] = '未读取到'

            try:
                Choose_Pattern = customizationData[2]['optionSelection']['label']
                values['Choose_Pattern'] = Choose_Pattern
            except:
                values['Choose_Pattern'] = '未读取到'

            try:
                # 具体内容部分
                ContainerCustomization = customizationData[3]['children']
            except:
                return

            try:
                Font = ContainerCustomization[0]['fontSelection']['family']
                values['Font'] = Font
            except:
                values['Font'] = '未读取到'

            try:
                # 展示信息部分
                PlacementContainerCustomization = ContainerCustomization[2]["children"]
            except:
                return

            try:
                Front_Side = PlacementContainerCustomization[0]["children"][0]['inputValue']
                values["Pet's Name"] = Front_Side
            except:
                values["Pet's Name"] = '未读取到'

            try:
                Text_1 = PlacementContainerCustomization[1]["children"][0]['inputValue']
                values['Text_1'] = Text_1
            except:
                values['Text_1'] = '未读取到'

            try:
                Text_2 = PlacementContainerCustomization[2]["children"][0]['inputValue']
                values['Text_2'] = Text_2
            except:
                values['Text_2'] = '未读取到'

            try:
                Text_3 = PlacementContainerCustomization[3]["children"][0]['inputValue']
                values['Text_3'] = Text_3
            except:
                values['Text_3'] = '未读取到'

            try:
                Text_4 = PlacementContainerCustomization[4]["children"][0]['inputValue']
                values['Text_4'] = Text_4
            except:
                values['Text_4'] = '未读取到'

            try:
                Selection_4 = customizationData[4]['optionSelection']['label']
                values['Selection_4'] = Selection_4
            except:
                values['Selection_4'] = '未读取到'

        return values

    @staticmethod
    def read_path(src_path: Path):
        """读取文件路径"""
        file_paths = []
        for file in src_path.iterdir():
            if file.is_file() and file.suffix == '.zip':
                file_paths.append(file)
        return file_paths
    
    @staticmethod
    def write_txt(values: dict, path: Path):
        """将读取到的关键信息写入到txt"""
        try:
            txt_name = values['orderId'] + '_' + values['orderItemId']
            txt_path = path / f"{txt_name}.txt"

            with open(txt_path, mode='w', encoding='utf-8') as txt:
                print('values:', values)
                for key, value in values.items():
                    if key == 'name':
                        continue
                    if key == 'Text_1':
                        txt.writelines('Text：\n')
                    if 'Text' in key:
                        if value == '未读取到':
                            continue
                        txt.writelines([value, '\n'])
                    else:
                        if key == 'Selection_4':
                            if value == '未读取到':
                                continue
                        txt.writelines([key, '：', value, '\n'])
            
            return txt_path
        except:
            print('zip内目标文件具有差异性，不能读取所有目标信息！')

    @staticmethod
    def remove_useless_files(path: Path):
        """删除无用文件"""
        for root, dirs, files in os.walk(path):
            for file in files:
                file_path = Path(root) / file
                if file_path.suffix in {'.jpg', '.json'}:
                    file_path.unlink()


if __name__ == '__main__':
    src_path = ""
    dst_path = ""
    file_paths = GetInformation.read_path(src_path)
    if len(file_paths) < 1:
        print('没有需要读取信息的zip文件')
    else:
        for file_path in file_paths:
            GetInformation.uncompress_svg(file_path)
            values = GetInformation.read_property(file_path)
            # print(values)
            dir_path = os.path.dirname(file_path)
            txt_path = GetInformation.write_txt(values, dir_path)
            jpg_path = GetInformation.uncompress_jpg(file_path)

        print('已将所有zip文件里需要读取的信息分别提取到txt文件中！')
